﻿namespace Okazuki.MVVM.PrismSupport.Utils
{
    using System;
    using System.Collections.Generic;

    /// <summary>
    /// コマンド管理クラス
    /// </summary>
    public static class CommandManager
    {
        private static List<WeakReference> canExecuteChangeds = new List<WeakReference>();

        public static event EventHandler RequerySuggested
        {
            add
            {
                canExecuteChangeds.Add(new WeakReference(value));
            }

            remove
            {
                canExecuteChangeds.Remove(new WeakReference(value));
            }
        }

        public static void InvalidateRequerySuggested()
        {
            lock (canExecuteChangeds)
            {
                for (int i = canExecuteChangeds.Count - 1; i >= 0; i--)
                {
                    var reference = canExecuteChangeds[i];
                    if (reference.IsAlive)
                    {
                        var h = reference.Target as EventHandler;
                        if (h != null)
                        {
                            h(null, EventArgs.Empty);
                        }
                    }
                    else
                    {
                        canExecuteChangeds.RemoveAt(i);
                    }
                }
            }
        }
    }
}
